package com.mengxuegu.gateway.filter;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengxuegu.gateway.config.IgnoreUrlsConfig;
import com.mengxuegu.gateway.utils.EncryptUtil;
import com.mengxuegu.gateway.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * 自定义路由过滤器
 * 路由过滤器可用于修改进入的http请求和返回的http相应，路由过滤器只能指定路由进行使用
 */
@Component
@Slf4j
public class GatewayAuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private IgnoreUrlsConfig properties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        List<String> ignoreUrls = properties.getUrls();
        log.info("不需要认证的所有请求路径：{}", ignoreUrls);
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, requestUrl)) {
                log.info("白名单：{} 请求不需要认证", requestUrl);
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        String token = TokenUtil.getToken(exchange);
        if (token == null) {
            return TokenUtil.noTokenMono(exchange);
        }
        //3.判断是不是有效的token
        OAuth2AccessToken oAuth2AccessToken;
        try {
            oAuth2AccessToken = tokenStore.readAccessToken(token);
            Map<String, Object> additionalInformation = oAuth2AccessToken.getAdditionalInformation();
            //取出用户身份信息
            String principal = MapUtil.getStr(additionalInformation, "user_name");
            //获取用户的权限
            Object authorities = additionalInformation.get("authorities");

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("principal", principal);
            jsonObject.put("authorities", authorities);
            String jsonToken = EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonObject));
            ServerHttpRequest tokenRequest = exchange.getRequest().mutate().header("json-token", jsonToken).build();
            ServerWebExchange build = exchange.mutate().request(tokenRequest).build();
            return chain.filter(build);
        } catch (InvalidTokenException e) {
            log.info("无效的token: {}", token);
            return chain.filter(exchange);
        }

    }

    @Override
    public int getOrder() {
        return -600;
    }



}
